package com.aggregate.pay.weixin.support;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.weixin.bean.AbstractData;
import com.aggregate.pay.weixin.support.utils.MD5;
import com.aggregate.pay.weixin.support.utils.XML;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 微信官方支付工具类
 * @author Moyq5
 * @date 2018年6月16日
 */
public class Tool {
	
	private static final Logger log = LoggerFactory.getLogger(Tool.class);

	public static String sign(String xml, String key) throws Exception {
		Map<String, Object> map = XML.toObject(xml, new TypeReference<TreeMap<String, Object>>() {});
		map.remove("sign");// sign参数不参与签名
		
		StringBuffer sb = new StringBuffer();
		for (Entry<String, Object> entry: map.entrySet()) {
			if (null != entry.getValue() && !String.valueOf(entry.getValue()).isEmpty()) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		sb.append("key=" + key);

		log.debug("签名内容：{}", sb.toString());
		String sign = MD5.MD5Encode(sb.toString()).toUpperCase();
		log.debug("签名值：{}", sign);
		return sign;
	}
	
	public static <T extends AbstractData> T sign(T data, String key) throws Exception {
		data.setSign(sign(XML.toXml(data), key));
		return data;
	}
	
}
